<?php

namespace App\Http\Controllers\Api\V1;


use App\Models\Coach;
use App\Models\Subscribe;
use App\Repositories\PutimesRepository;
use App\Transformers\PutimeLogTransformer;
use App\Models\TcpPutime;
use App\Models\TcpStudytime;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

class PutimeController extends BaseController
{
    protected $putimes;

    public function __construct(
        PutimesRepository $putimesRepository
    )
    {
        $this->putimes = $putimesRepository;
    }

    /**
     * @api {get} /putime 我的培训(putime list)
     * @apiDescription 我的培训(putime list)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [type=1]  类型  1：科目一 2：科目二 3：科目三  4：科目四
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": {
     *            "syllabus": [  //教学大纲规定学时
     *              {
     *                  "id": 1,
     *                  "km": 1, //科目
     *                  "title": "第一部分  道路交通安全法律、法规和相关知识",//标题
     *                  "traintype": "C1",//类别
     *                  "hour": 12,//大纲要求学时
     *                  "accomplish":10//已完成学时 分钟min
     *              },
     *              {
     *                  "id": 4,
     *                  "km": 2,
     *                  "title": "第二部分  基础和场地驾驶",
     *                  "traintype": "C1",
     *                  "hour": 16,
     *                  "accomplish":10//已完成学时 分钟min
     *              },
     *              {
     *                  "id": 7,
     *                  "km": 3,
     *                  "title": "第三部分  道路驾驶",
     *                  "traintype": "C1",
     *                  "hour": 24,
     *                  "accomplish":10//已完成学时 分钟min
     *              },
     *              {
     *                  "id": 10,
     *                  "km": 4,
     *                  "title": "第四部分  安全文明驾驶常识",
     *                  "traintype": "C1",
     *                  "hour": 10,
     *                  "accomplish":10//已完成学时 分钟min
     *              }
     *          ],
     *          "count": {
     *              "km1theory": 3,//科一理论
     *              "km1scene": 0,//科一面授
     *              "km2operation": "754",//科二实操 min
     *              "km3operation": "162",//科三实操 min
     *              "km4theory": 0,//科四理论
     *              "km4scene": 0//科四面授
     *          },
     *          "log": [
     *          {
     *              "id":112,主键id
     *              "inscode": "4373360266622780", //驾校编号
     *              "stunum": "2553968135259455",//学员编号
     *              "coachnum": "",//教练编号
     *              "carnum": "",//车辆编号
     *              "simunum": "",//设备编号
     *              "subjcode": "4211030000",//学时编号
     *              "classid": "1493357359",//课堂编号
     *              "km": 1,//科目
     *              "type": 4,//学时类型  1：面授 2：实操 3：模拟 4：理论
     *              "starttime": "2017-04-28 12:29:15",//学时开始时间
     *              "endtime": "2017-04-28 13:29:15",//学时结束时间
     *              "duration": 60,//该次培训学时上传的培训时长 单位：min
     *              "mileage": 0,//该次培训学时上传的培训里程 单位：0.1km
     *              "is_evaluate":0,//是否评论 1：已评论
     *              "is_complaint":0,//是否投诉  1：已投诉
     *              "valid": 60,//有效学时 min
     *              "coachname": "",//教练姓名
     *              "licnum": "",//车牌号
     *              "classname": "第一部分综合复习及考核"//课程名称
     *          }
     *          ]
     *       }
     *   }
     */
    public function index(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        if($user->item_type != 'App\Models\Student'){return $this->errorResponse('无访问权限');}
        //参数
        $parem = [
            'userid'=>$user->item_id,
            'name'=>$user->name,
            'type'=>$request->get('type'),
        ];
        $list = $this->putimes->index($parem);
        if(!$list){
            return $this->errorResponse($this->putimes->error);
        }
        return $this->successResponse('success',['data'=>$list]);
    }

    /**
     * @api {get} /putime/log 电子教学日志(putime log)
     * @apiDescription 电子教学日志(putime log)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/log
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [type=1]  类型  1：全部 2：未评价 3：已投诉
     * @apiParam {Number} [page=1]  page
     * @apiParam {Number} [size=10]  size
     * @apiParam {Number} [km]  km
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
     *           "count": {
     *           "evaluatenum": 136,//待评论总数
     *           "complaintnum": 0,//已投诉总数
     *           },
     *
     *          list[
     *            {
     *               "id": 70916, //id主键
     *               "inscode": "4373360266622780",//驾校编号
     *               "coachnum": "",//教练编号
     *               "coachname": "",//教练姓名
     *               "carnum": "",//车辆编号
     *               "licnum": "",//车牌号
     *               "simunum": "",//设备编号
     *               "subjcode": "4211030000",//学时编号
     *               "classname": "第一部分综合复习及考核",//课堂名称
     *               "classid": "1493357359",//课堂编号
     *               "km": 1,//科目
     *               "type": 4,//学时类型  1：面授 2：实操 3：模拟 4：理论
     *               "starttime": "2017-04-28 12:29:15",//学时开始时间
     *               "endtime": "2017-04-28 13:29:15",//学时结束时间
     *               "duration": 60,//该次培训学时上传的培训时长 单位：min
     *               "mileage": 0,//该次培训学时上传的培训里程 单位：0.1km
     *               "valid": 60,//有效学时 min
     *               "is_evaluate": 0,//是否评论  1：已评论
     *               "is_complaint": 0//是否投诉  1：已投诉
     *           },
     *          ]
     *       ]
     *   }
     */
    public function putimeLog(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        if($user->item_type != 'App\Models\Student'){return $this->errorResponse('无访问权限');}
        //参数
        $parem = [
            'userid'=>$user->item_id,
            'name'=>$user->name,
            'type'=>$request->get('type'),
            'page'=>$request->get('page',1),
            'km' => $request->get('km')
        ];

        $size = $request->get('size', 10);

        $list = $this->putimes->putimeLog($parem,'', $size);

        if(!$list){
            return $this->errorResponse($this->putimes->error);
        }

        $transformer = new PutimeLogTransformer;

        foreach($list['list'] as $k => $putime){
            $list['list'][$k] = $transformer->transform($putime);
        }

        return $this->successResponse('success',['data'=>$list]);

    }

    /**
     * @api {get} /putime/teachingRecord 教学记录(putime teachingRecord)
     * @apiDescription 教学记录(putime teachingRecord)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/teachingRecord
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id=]  电子教学日志id
     * @apiParam {Number} [type=1]  类型  1：详情   2：轨迹  3：图表
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *  {
     *      "message": "success",
     *      "status_code": 200,
     *      "data": {
     *          "list": {
     *              "valid_putime": 0,//有效学时
     *              "novalid_putime": 0,//无效学时
     *              "km": 1,//科目
     *              "type": 1,//教学日志类型 1：面授  2：实操  3：模拟教学 4远程教学
     *              "starttime": "2017-04-28 15:34:07",//开始时间
     *              "endtime": "2017-04-28 15:34:22",//结束时间
     *              "duration": 0,//时长 min
     *              "mileage": 0,//里程  0.1千米
     *              "coachname": "傅蕾蕾",//教练姓名
     *              "licnum": "川A3824学",//车牌号
     *              "classname": "第一部分综合复习及考核"//课程名称
     *          },
     *          "img": [
     *              {
     *                  "img_type": 17, //图片类型 17：学员登陆拍照  18：学员登出拍照  19：培训过程拍照
     *                  "img_url": "http://img.exc360.com/photo/2017/03/30/1490855913_sPS.jpg", //图片地址
     *                  "ptime": "2017-04-28 15:34:07"//时间
     *              },
     *              {
     *                  "img_type": 18,
     *                  "img_url": "http://img.exc360.com/photo/2017/03/30/1490855913_sPS.jpg",
     *                  "ptime": "2017-04-28 15:34:22"
     *              }
     *          ]
     *      }
     *  }
     */
    public function teachingRecord(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $parem = [
            'putime_id'=>$request->get('putime_id'),
            'type'=>$request->get('type',1),
            'userid' => $user->item_id,
        ];
        if(!$parem['putime_id']){
            return $this->errorResponse('参数错误');
        }
        $list = $this->putimes->teachingRecord($parem);
        return $this->successResponse('success',['data'=>$list]);
    }


    /**
     * @api {get} /putime/latestRecord 最近教学记录
     * @apiDescription 最近教学记录(putime teachingRecord)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/latestRecord
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [size] size
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *  {
     *      "message": "success",
     *      "status_code": 200,
     *      "data": {
     *          "list": {
     *              "valid_putime": 0,//有效学时
     *              "novalid_putime": 0,//无效学时
     *              "km": 1,//科目
     *              "type": 1,//教学日志类型 1：面授  2：实操  3：模拟教学 4远程教学
     *              "starttime": "2017-04-28 15:34:07",//开始时间
     *              "endtime": "2017-04-28 15:34:22",//结束时间
     *              "duration": 0,//时长 min
     *              "mileage": 0,//里程  0.1千米
     *              "coachname": "傅蕾蕾",//教练姓名
     *              "licnum": "川A3824学",//车牌号
     *              "classname": "第一部分综合复习及考核"//课程名称
     *          },
     *          "img": [
     *              {
     *                  "img_type": 17, //图片类型 17：学员登陆拍照  18：学员登出拍照  19：培训过程拍照
     *                  "img_url": "http://img.exc360.com/photo/2017/03/30/1490855913_sPS.jpg", //图片地址
     *                  "ptime": "2017-04-28 15:34:07"//时间
     *              },
     *              {
     *                  "img_type": 18,
     *                  "img_url": "http://img.exc360.com/photo/2017/03/30/1490855913_sPS.jpg",
     *                  "ptime": "2017-04-28 15:34:22"
     *              }
     *          ]
     *      }
     *  }
     */
    public function latestRecord(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $size = $request->input('size', 7);

            //获取最新的培训科目
        $list = TcpStudytime::select('starttime','endtime','km','created_at','classid','type','duration','id')->where('stunum', $user->item->stunum)->orderBy('created_at', 'desc')->limit($size)->get();

        if(count($list)){
            foreach($list as $latest_train){

                $latest_train->valid_putime = TcpPutime::where('stunum',$latest_train->stunum)->where('classid',$latest_train->classid)->where('jishi_check',1)->where('jg_check',1)->count();//有效学时
                $latest_train->novalid_putime = TcpPutime::where('stunum',$latest_train->stunum)->where('classid',$latest_train->classid)->where('jg_check',2)->count();//无效学时

            }
        }

        return $this->successResponse('success', ['data'=>$list]);
    }


    /**
     * @api {get} /putime/getNovalidPutime 无效学时数据(putime getNovalidPutime)
     * @apiDescription 无效学时数据(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/getNovalidPutime
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [class_id=] 课程id
     * @apiParam {Number} [page=] page
     * @apiParam {Number} [size=] size
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
                    {
                        "id": 3176,
                        "log_id": null,
                        "devnum": "5190187375504752",
                        "stunum": "2553968135259455",
                        "coachnum": "4151666593540518",
                        "recno": "51901873755047521612300902",
                        "classid": "1483081273",
                        "subject": "1212000000",
                        "km": 2,
                        "rptype": 1,
                        "rttype": 0,
                        "state": 0,
                        "runningspeed": 0,//行驶速度
                        "maxspeed": 0,
                        "rev": 975,
                        "mileage": 0,//行驶距离
                        "lon": "116392676",
                        "lat": "39962481",
                        "rectime": "2016-12-30 15:02:13",
                        "updated_at": "2016-12-30 15:02:13",
                        "created_at": "2016-12-30 15:02:13", //记录时间
                        "jishi_check": 2,
                        "jishi_check_reason": "速度超过最大停止时间",//不合格原因
                        "jg_check": 0,
                        "jg_check_reason": null
                    }
              ]
     *   }
     */
    public function getNovalidPutime(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $class_id = $request->get('class_id');
        $page = $request->get('page',1);
        $size = $request->get('size',10);

        if(!$class_id){
            return $this->errorResponse('参数错误');
        }
        $list = $this->putimes->noValidePutime($user->item, $class_id, $page, $size);

        return $this->successResponse('success',['data'=>$list]);
    }


    /**
     * @api {get} /putime/complainInfo 获取培训投诉的信息(putime getNovalidPutime)
     * @apiDescription 获取培训投诉的信息(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/complainInfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id=] 培训ID
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
                    {
                    }
               ]
     *   }
     */
    public function complainInfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }


        $putime_id = $request->input('putime_id');

//        $putime_info = $this->putimes->getById($putime_id);
        $putime_info = Subscribe::leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                                ->select('yy_put_periods.km','yy_put_periods.startime','yy_put_periods.endtime','yy_subscribes.coach_id')
                                ->find($putime_id);

        $data = [];
        if($putime_info){

            $coach = Coach::find($putime_info->coach_id);

            $data['coachname'] = $coach ? $coach->name : '';
            $data['km'] = $putime_info->km;
            $data['starttime'] = $putime_info->startime;
            $data['endtime'] = $putime_info->endtime;
        }

        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {post} /putime/postComplainInfo 提交培训投诉的信息(putime getNovalidPutime)
     * @apiDescription 提交培训投诉的信息(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/postComplainInfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [content=] content
     * @apiParam {Number} [putime_id=] putime_id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
    {
    }
    ]
     *   }
     */
    public function postComplainInfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $content = $request->input('content');
        $putime_id = $request->input('putime_id');

        $this->putimes->complain($user->item, $putime_id, $content);

        return $this->successResponse('投诉成功');
    }


    /**
     * @api {get} /putime/showComplainInfo 查看培训投诉的信息(putime getNovalidPutime)
     * @apiDescription 查看培训投诉的信息(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/showComplainInfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id=] putime_id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
    {
    }
    ]
     *   }
     */
    public function showComplainInfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $putime_id = $request->input('putime_id');

        $data = $this->putimes->showComplaint($user->item, $putime_id);

        return $this->successResponse('success', ['data' => $data]);
    }



    /**
     * @api {post} /putime/postCommentInfo 提交培训评价的信息(putime getNovalidPutime)
     * @apiDescription 提交培训评价的信息(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/postCommentInfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id=] 培训ID
     * @apiParam {Number} [type=] 0：不满意   1：满意   2：非常满意',
     * @apiParam {String} [content=] content
     * @apiParam {Number} [to_type=] to_type 评价对象 1培训实车记录，2预约学车记录
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
    {
    }
    ]
     *   }
     */
    public function postCommentInfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $putime_id = $request->input('putime_id');

        $data['content'] = $request->input('content');
        $data['type'] = $request->input('type');
        $data['to_type'] = $request->input('to_type', 2);

        $this->putimes->comment($user->item, $putime_id, $data);

        return $this->successResponse('评价成功');
    }


    /**
     * @api {get} /putime/showCommentInfo 查看培训评价的信息(putime getNovalidPutime)
     * @apiDescription 查看培训评价的信息(putime getNovalidPutime)
     * @apiGroup Putime
     * @apiSampleRequest /api/putime/showCommentInfo
     * @apiPermission none
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Number} [putime_id=] putime_id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *   {
     *       "message": "",
     *       "status_code": 200,
     *       "data": [
    {
    }
    ]
     *   }
     */
    public function showCommentInfo(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        if(!$this->checkToken($user->item, JWTAuth::getToken())){
            return $this->errorResponse('你的账号在其他地方登录', 401);
        }

        $putime_id = $request->input('putime_id');

        $data = $this->putimes->showComment($user->item, $putime_id);

        return $this->successResponse('success', ['data' => $data]);
    }
}
